#include "RedisCache.h"

RedisCache::RedisCache()
: _pConnect(nullptr)
, _pReply(nullptr)
{

}

RedisCache::~RedisCache()
{
    if(_pConnect)
    {
        redisFree(_pConnect);
        _pConnect = nullptr;
    }

    if(_pReply)
    {
        freeReplyObject(_pReply);
        _pReply = nullptr;
    }
}

bool RedisCache::connect(const string &host,int port)
{
    _pConnect = redisConnect(host.c_str(),port);
    if(_pConnect == nullptr)
    {
        return false;
    }

    if(_pConnect != nullptr && _pConnect->err)
    {
        std::cerr << "connect error" << _pConnect->errstr <<endl;
        return false;
    }

    return true;
}

void RedisCache::keySet(string key,string value)
{
    int dbNumber = 0;
    _pReply = (redisReply*)redisCommand(_pConnect, "SELECT %d", dbNumber);
    _pReply = (redisReply *)redisCommand(_pConnect,"SET %s %s",key.c_str(),value.c_str());
    if(_pReply)
    {
        freeReplyObject(_pReply);
        _pReply = nullptr;
    }
}

void RedisCache::webSet(string key,string value)
{
    int dbNumber = 1;
    _pReply = (redisReply*)redisCommand(_pConnect, "SELECT %d", dbNumber);
    _pReply = (redisReply *)redisCommand(_pConnect,"SET %s %s",key.c_str(),value.c_str());
    if(_pReply)
    {
        freeReplyObject(_pReply);
        _pReply = nullptr;
    }
}

string RedisCache::getKey(string key)
{
    int dbNumber = 0;
    _pReply = (redisReply*)redisCommand(_pConnect, "SELECT %d", dbNumber);
    _pReply = (redisReply *)redisCommand(_pConnect,"GET %s",key.c_str());
    if(_pReply)
    {
        if(_pReply->type == REDIS_REPLY_STRING)
        {
            string str = _pReply->str;
            freeReplyObject(_pReply);
            _pReply = nullptr;

            //json jsonStr = str; 
            
            return str;
        }
        else
        {
            return "";
        }
    }
    else
    {
        return "";
    }
}

string RedisCache::getWeb(string key)
{
    int dbNumber = 1;
    _pReply = (redisReply*)redisCommand(_pConnect, "SELECT %d", dbNumber);
    _pReply = (redisReply *)redisCommand(_pConnect,"GET %s",key.c_str());
    if(_pReply)
    {
        if(_pReply->type == REDIS_REPLY_STRING)
        {
            string str = _pReply->str;
            freeReplyObject(_pReply);
            _pReply = nullptr;

            //json jsonStr = str; 
            
            //return jsonStr;
            return str;
        }
        else
        {
            return "";
        }
    }
    else
    {
        return "";
    }
}